//
//  CategoryViewController.swift
//  1604_LimitFree
//
//  Created by 千锋 on 16/9/28.
//  Copyright © 2016年 Mabin. All rights reserved.
//

import UIKit
protocol CategoryViewControllerDelegate : NSObjectProtocol
{
    func didClickCateId(cateId : String, cateName : String)
}

//分类的类型
public enum CategoryType : Int
{
    case LimitFree  //限免
    case Reduce     //降价
    case Free       //免费
}

class CategoryViewController: LFBaseViewController {

    //类型
    var type : CategoryType?
    
    //代理属性
    weak var delegate : CategoryViewControllerDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.whiteColor()
    }
    
    //导航
    override func createMyNav() {
        //标题文字
        var titleStr = ""
        if type == .LimitFree
        {
            titleStr = "限免-分类"
        }
        else if type == .Reduce
        {
            titleStr = "降价-分类"
        }
        else if  type == .Free
        {
            titleStr = "免费-分类"
        }
        addnavTitle(titleStr)
        
        
        //返回按钮
        addBackButton()
        
    }
    
    //下载
    override func downloaderData() {
        //菊花
        ProgressHUD.showOnView(view)
        var urlString :String? = nil
        
        if type == .LimitFree
        {
            urlString = kCategoryLimitUrl
        }
        else if type == .Reduce
        {
            urlString = kCategoryReduceUrl
        }
        else if type == .Free
        {
            urlString = kCategoryFreeUrl
        }
        if urlString != nil
        {
            let download = LFDownloader()
            download.delegate = self
            download.downloadWithURLString(urlString!)
        }
    }
    
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 80
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cellId = "categoryCellId"
        var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CategoryCell
        if cell == nil
        {
            cell = NSBundle.mainBundle().loadNibNamed("CategoryCell", owner: nil, options: nil).last as? CategoryCell
        }
        
        let model = dataArray[indexPath.row] as! CategoryModel
        cell?.configModel(model,type: type!)
        return cell!
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let model = dataArray[indexPath.row] as! CategoryModel
        let cateId = "\(model.categoryId!)"
        let cateName = MyUtil.transferCateName(model.categoryName!)
        delegate?.didClickCateId(cateId, cateName: cateName)
        self.navigationController?.popToRootViewControllerAnimated(true)
    }
    
}

extension CategoryViewController : LFDownloaderDelegate
{
    func downloader(downloader: LFDownloader, didFailWithError error: NSError) {
        ProgressHUD.hideAfterFailOnView(self.view)
    }
    
    func downloader(downloader: LFDownloader, didFinishWithData data: NSData) {
        
        let result = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
        if result.isKindOfClass(NSDictionary)
        {
            let dict = result as! Dictionary<String,AnyObject>
            let array = dict["category"] as! Array<Dictionary<String,AnyObject>>
            for tmpDict in array
            {
                let cateId = tmpDict["categoryId"]
                let cateIdStr = "\(cateId!)"
                if cateIdStr == "0"
                {
                    continue
                }
                let model = CategoryModel()
                model.setValuesForKeysWithDictionary(tmpDict)
                dataArray.addObject(model)
            }
            dispatch_async(dispatch_get_main_queue(), {
                
                self.tableView?.reloadData()
                
                ProgressHUD.hideAfterSuccessOnView(self.view)
            })
        }
    }
}
